<?php

/**
 * [WeEngine System] Copyright (c) 2013 WE7.CC
 * User: fanyk
 * Date: 2017/12/10
 * Time: 14:46.
 */

include IA_ROOT . '/addons/bh_bargain/lib/function.php';
include IA_ROOT . '/addons/bh_bargain/lib/WxpayAPI_php_v3/WxpayAPI_php_v3.php';
include IA_ROOT . '/addons/bh_bargain/lib/WXBizDataCrypt.php';

include 'controller/common.php';
include 'model/bargain.mod.php';
include 'model/vote.mod.php';
include 'lib/Wxadoc.php';
include 'lib/Qqadoc.php';

class bh_bargainModuleWxapp extends WeModuleWxapp {


    public $action = '';
    public $contr = '';

    public function __construct() {
        global $_W;
        define('UNIACID', $_W['uniacid']);
    }




    public function doPageDistribute()
    {
        global $_GPC;
        $this->action = $_GPC['action'] ? : 'index';
        $this->contr = $_GPC['contr'] ? : 'index';

        include_once "controller/{$this->contr}.php";

        $c = new $this->contr;

        if (method_exists($c, $this->action)) {
            $c->{$this->action}();
        }
    }


    public function createUrl($do, $query = array())
    {
        global $_W;
        $url = $_W['siteroot'] . "/index.php?i=" . UNIACID . "&from=wxapp&c=entry&a=wxapp&do={$do}&m=bh_rising&";
        if ($query) {
            $queryString = http_build_query($query, '', '&');
            $url .= $queryString;
        }
        return $url;
    }




    /**
     * 计划任务
     */
    public function doPageCrontab()
    {

        global $_W;
        $option = array(
            'appid' => $_W['uniaccount']['key'],
            'secret' => $_W['uniaccount']['secret'],
        );
        $wxObj = new Wxadoc($option);
        $time = strtotime(date('Y-m-d', time()));
        $profit_subscribe_id = getConfig('profit_subscribe_id');

        $h = date('H');
        $i = date('i');
        $money_send_hour    = getConfig('earnings_send_hour');
        $money_send_minute  = getConfig('earnings_send_minute');

        $reward_type = getConfig('reward_type', 1);
        $dayCount = p_getcolumn('day', array('same_day' => $time - 86400, 'is_fictitious' => 1), 'sum(currency)');
        $content2 = array(
            'thing1' => array('value' =>"昨日打卡奖励已经发放啦"),
            'thing2' => array('value' =>"请点击进入我的页面查看"),
        );
        if (!p_get('system_day', array('same_day' => $time - 86400))) {
            $same_day =  $time - 86400;
            $virtualDayCount = p_getcolumn('day', array('same_day' => $time - 86400, 'is_fictitious' => 2), 'sum(currency)');
            $daySql = "SELECT COUNT(*) as total_number  FROM ". prefix('day'). " WHERE same_day = ". $same_day . " AND  clock > 0 AND uniacid =".UNIACID;
            $total_number = p_fetch($daySql);
            $systemDayData = array(
                'same_day'          => $time - 86400,
                'fictitious_currency' => $virtualDayCount,
                'fictitious_money' => $virtualDayCount * getConfig('currency_money'),
                'click_num'     => p_getcolumn('day', array('same_day' => $time - 86400), 'SUM(clock)'),
                'total_number'  => $total_number['total_number'],
                'created'       => time()
            );
            p_insert('system_day', $systemDayData);
        }

        if ($profit_subscribe_id && ($money_send_hour < $h || ($money_send_hour == $h && $money_send_minute <= $i))) {
            if ($sameDay = p_get('system_day', array('same_day' => $time - 86400))) {
                $systemDayData = array(
                    'currency'      => $dayCount,
                    'money'         => $reward_type == 1  ? $dayCount * getConfig('currency_money') : getConfig('pool'),
                );
                p_update('system_day', $systemDayData, array('id' => $sameDay['id']));
            }
            //$pool = getConfig('pool');
            //$currency_money = getConfig('currency_money');
            $rising = new  rising();

            while (true) {
              $syn = p_get('crontab_data', array('time' => $time - 86400));
                if (empty($syn)) {
                    $syn = array(
                        'day_id' => 0,
                        'time'   => $time - 86400
                    );
                    p_insert('crontab_data', $syn);
                    $syn['id'] = pdo_insertid();

                }
                $yesterday = $time - 86400 ;
                $sql = 'SELECT * FROM '.prefix('day').' WHERE id >' . $syn['day_id'] . ' AND status = 1 AND is_fictitious=1 AND same_day = '. $yesterday. ' AND uniacid= '.UNIACID.' ORDER bY id ASC LIMIT 10';
                $data = pdo_fetchall($sql);
                if (empty($data)) {
                    break;
                }
                foreach ($data as $value) {
                    $money = $this->getMoney($dayCount, $value['currency'], $reward_type);
                    $member = p_get('member', array('id' => $value['member_id'], 'is_block' => 1));
                    if (empty($member)) {
                        p_update('day',array('status' => 2, 'updated' => time()), array('id' => $value['id']));
                        continue;
                    }
                    $is_bonus = getConfig('is_bonus');
                    if ($is_bonus != 2) {
                        p_update('day',array('money' => $money,'status' => 2, 'updated' => time()), array('id' => $value['id']));
                    } else {
                        p_update('day',array('status' => 2, 'updated' => time()), array('id' => $value['id']));
                    }
                    if (!empty($member['openid'])) {
                        if($is_bonus !=2 ) {
                            $memberCount = p_getcolumn('day', array('same_day' => $yesterday, 'member_id' => $member['id']), 'clock');
                            if ($memberCount > getConfig('click_num_bonus')) {
                                $rising->change_money($member['id'], $money);
                            }
                            if (getConfig('is_bonus_deduction') == 2) {
                                $rising->change_currency($member['id'],  $value['currency'], 6, '分红扣出');
                            }
                        }
                        if ($member['remind'] > 0) {
                            $s = $wxObj->sendSubscribe($member['openid'], $profit_subscribe_id,'bh_rising/pages/index/index', $content2);
                            var_dump($s);
                            p_update('member', array('remind' => $member['remind'] - 1 ), array('id' => $member['id']));
                        }
                    }
                    $data = array(
                        'day_id' => $value['id'],
                        'time'   => $time
                    );
                    if (!p_update('crontab_data', $data, array('id' => $syn['id']))) {
                         die('修改失败');
                    }
                }
            }
        }
        json('success') ;
    }


    public function doPageKjCrontabDy()
    {
        $sql = ('SELECT * FROM ' . prefix('luck') . ' WHERE status = 1 AND complete = 2 AND lottery_type=1 AND lottery_value<=' . time() . get_uniacid());

        $lottery = p_fetchall($sql);
        $vote = new vote();
        if ($lottery) {
            foreach ($lottery as $value) {
                $vote->lottery($value['id']);
            }
        }

        $luck = p_getall('luck', array('send_msg' => 2));
        $dy_send_message_kj_id = getConfig('dy_send_message_kj_id');
        if ($luck) {
            $t = time() - (7 * 86400);
            global $_W;
            $option = array(
                'appid' => $_W['uniaccount']['key'],
                'secret' => $_W['uniaccount']['secret'],
            );
            $wxObj = new Wxadoc($option);

            foreach ($luck as $value) {
                $luck_goods =  p_getcolumn('luck_goods', array('luck_id' => $value['id']), 'name');
                $content = array(
                    'thing1' => array('value' => mb_substr($luck_goods, 0, 18)),
                    'thing2' => array('value' => "您参与的抽奖已开奖,点击查看"),
                );
                while (true) {
                    $participate = p_get('luck_participate', array('luck_id' => $value['id'], 'msg_status' => 1));
                    if (empty($participate)) {
                        p_update('luck', array('send_msg' => 3), array('id' => $value['id']));
                        //$f_form_id = p_fetch('SELECT * FROM ' . prefix('form_id') . " WHERE member_id={$value['member_id']} AND created > {$t}");
                        $f_openid = p_getcolumn('member', array('id' => $value['member_id']), 'openid');
                        if ($f_openid) {
                            $content2 = array(
                                'thing1' => array('value' => mb_substr($luck_goods, 0, 18)),
                                'thing2' => array('value' => "您发起的抽奖正在开奖,点击查看"),
                            );
                            $s = $wxObj->sendSubscribe($f_openid, $dy_send_message_kj_id, 'bh_bargain/pages/userGame/userGame?id=' . $value['id'], $content2);
                            var_dump($s);
                            p_update('luck_participate', array('msg_status' => 2), array('id' => $participate['id']));
                        }
                        break;
                    }
                    //$form_id = p_fetch('SELECT * FROM ' . prefix('form_id') . " WHERE member_id={$participate['member_id']} AND created > {$t}");
                    $openid = p_getcolumn('member', array('id' => $participate['member_id']), 'openid');
                    if ($openid) {
                        $s_s = $wxObj->sendSubscribe($openid, $dy_send_message_kj_id, 'bh_bargain/pages/userGame/userGame?id=' . $value['id'], $content);
                        var_dump($s_s);
                    }

                    p_update('luck_participate', array('msg_status' => 2), array('id' => $participate['id']));
                }
            }



        }
        echo 'okKJ';
    }


    public function doPageActivitySend()
    {
        while (true) {
            $subscribeQueue =  p_getall('subscribe_queue', array('status' => 1));
            if ($subscribeQueue) {
                global $_W;
                $option = array(
                    'appid' => $_W['uniaccount']['key'],
                    'secret' => $_W['uniaccount']['secret'],
                );
                $wxObj = new Wxadoc($option);
                $new_activities_id = getConfig('new_activities');
                foreach ($subscribeQueue as $value) {
                    $str = "SELECT * FROM " . prefix('subscribe'). " WHERE id >" .$value['subscribe_id'] . " AND new_activities > 0 AND uniacid =". UNIACID . " limit 10";
                    $memberData = p_fetchall($str);
                    if (empty($memberData)) {
                        p_update('subscribe_queue', array('status' => 2), array('id' => $value['id']));
                        continue;
                    }
                    $sendData = json_decode($value['content'], true);
                    $date = explode('-', $sendData['activityTime']);
                    $content = array(
                        'thing3' => array('value' => $sendData['activityName']),
                        'date2'  => array('value' => $date[0].'年'.$date[1]. '月'.$date[2].'日'),
                        'thing4' => array('value' => $sendData['activityText']),
                    );
                    foreach ($memberData as $val) {
                        $member = p_get('member', array('id' => $val['member_id']));
                        if ($member['openid']) {
                            if ($val['new_activities'] > 0) {
                                $s = $wxObj->sendSubscribe($member['openid'],  $new_activities_id , $sendData['skipUrl'], $content);
                                $returnData = json_decode($s, true);
                                if($returnData['errCode '] == 0) {
                                    $value['number']++;
                                    p_update('subscribe_queue', array('number' => $value['number'], 'subscribe_id' => $val['id']), array('id' => $value['id']));
                                }
                                p_update('subscribe', array('new_activities' => $val['new_activities'] -1), array('id' => $val['id']));
                                var_dump($returnData);
                            }
                        }
                    }
                }
            } else {
                break;
            }
        }


        echo 'okKJ';
    }

    /**
     *
     */
    public function doPageBargaining()
    {
        $today = strtotime(date('Y-m-d'));
        $sql = "SELECT * FROM ".prefix('order'). " WHERE `status` = 1 AND is_fictitious = 1 AND noticeTime != {$today} ORDER BY id DESC LIMIT 100";
        $order =  p_fetchall($sql);
        if ($order) {
            global $_W;
            $option = array(
                'appid' => $_W['uniaccount']['key'],
                'secret' => $_W['uniaccount']['secret'],
            );
            $wxObj = new Wxadoc($option);
            $dy_bargaining_process_id = getConfig('dy_bargaining_process_id');
            foreach ($order as $val) {
                $goodsName = p_getcolumn('goods', array('id' => $val['goods_id']), 'name');
                $friend    = p_getcolumn('order_bargain', array('order_id' => $val['id']), 'COUNT(*)');
                $money     = p_getcolumn('order_bargain', array('order_id' => $val['id']), 'SUM(money)');
                $content = array(
                    'thing1' => array('value'  => $goodsName),
                    'thing2' => array('value' => "已经有{$friend}个好友为你砍价{$money}元"),
                    'thing4' => array('value'  => "剩余时间已经不多,尽快召集好友砍价吧"),
                );
                $member = p_get('member', array('id' => $val['member_id']));
                if ($member['openid'] && $dy_bargaining_process_id) {
                    $s = $wxObj->sendSubscribe($member['openid'],  $dy_bargaining_process_id , '/bh_bargain/pages/bargain/bargain?id=' . $val['id'], $content);
                    $returnData = json_decode($s, true);
                    if($returnData['errCode '] == 0) {
                        p_update('order', array('noticeTime' =>  $today), array('id' => $val['id']));
                    }
                    var_dump($returnData);
                }
            }
        }
        echo 'okKJ';
    }

    protected function getMoney($dayCount, $currency, $reward_type)
    {
        $pool = getConfig('pool');
        $currency_money = getConfig('currency_money');
        if ($reward_type == 2) {
            $money = round($pool / $dayCount , 4) * $currency;
        } else {
            $money = $currency * $currency_money;
        }
        return $money;
    }

    public function doPageBatch()
    {
        $member  = p_fetchall('SELECT * FROM '.prefix('member')." WHERE is_fictitious = 2 ORDER BY id DESC LIMIT 0, 1000");
        if ($member) {
            $time = strtotime(date('Y-m-d', time()));
            foreach ($member as $value) {
                if (!p_get('day', array('same_day' => $time, 'member_id' => $value['id']))) {
                    $currency = mt_rand(getConfig('batch_start_currency'), getConfig('batch_end_currency'));
                    $data = array(
                        'member_id' => $value['id'],
                        'same_day'  => $time,
                        'clock'     => mt_rand(1, 10),
                        'currency'  => $currency,
                        'is_fictitious' => 2,
                        'created'   => time()
                    );
                    if (p_insert('day', $data)) {
                        (new rising())->change_currency($value['id'], $currency,4, '虚拟产生');
                    }
                }
            }
        }

        json('success');

    }


    public function doPageSignRemind()
    {
        $time = strtotime(date('Y-m-d', time()));
        $bargain = new bargain();
        while (true) {
            $remind =  p_getall('remind', array('status' => 1, 'type' => 1, 'remind_day' => $time), array(), '', array(), 20);
            if ($remind) {
                global $_W;
                $option = array(
                    'appid' => $_W['uniaccount']['key'],
                    'secret' => $_W['uniaccount']['secret'],
                );
                $wxObj = new Wxadoc($option);
                $sign_subscribe_id = getConfig('sign_subscribe');

                $h = date('H');
                $i = date('i');
                $money_send_hour    = getConfig('sign_subscribe_send_hour');
                $money_send_minute  = getConfig('sign_subscribe_send_minute');

                $content = array(
                    'thing1'  => array('value' => "签到成功"),
                    'thing4'  => array('value' => "获得积分奖励"),
                    'thing8'  => array('value' => "连续签到奖励更丰厚哦!,点击查看"),
                );
                if ($sign_subscribe_id && ($money_send_hour < $h || ($money_send_hour == $h && $money_send_minute <= $i))) {
                    foreach ($remind as $value) {
                        if ($bargain->is_sign($value['member_id'])) {
                            p_update('remind', array('status' => 3,'remind_time' => time()), array('id' => $value['id']));
                            continue;
                        }
                        $member = p_get('member', array('id' => $value['member_id']));
                        if ($member['openid']) {
                            $s = $wxObj->sendSubscribe($member['openid'], $sign_subscribe_id,'bh_bargain/pages/index/index', $content);
                            var_dump($s);
                            p_update('remind', array('status' =>2,'remind_time' => time()), array('id' => $value['id']));
                        }
                    }
                }
            } else {
                break;
            }
        }

        echo 'okKJ';
    }


    /**
     * 生成订单
     */
    public function doPageExchange()
    {
        $c = new bhCommon;

        $id = $c->get('id');
        if (empty($id)) {
            json('请先选择商品', 3);
        }

        $goods = p_get('goods', array('id' => $id, 'status' => 1, 'is_delete' => 1));

        if (empty($goods)) {
            $c->json('商品不存在或已下架', 3);
        }


        $volume = p_getcolumn('order', array('goods_id' => $id, 'is_pay' => 2), 'COUNT(*)') ? : 0;
        if ($volume >= $goods['inventory']) {
            $c->json('您来晚了,已经被兑换完了~', 3);
        }

        if ($goods['allow_number'] > 0) {
            if ($goods['allow_type'] == 1) {
                $buy_num = p_getcolumn('order', array('member_id' => $c->member['id'], 'goods_id' => $id, 'is_pay' => 2), 'COUNT(*)') ? : 0;
            } else {
                $t = strtotime(date('Y-m-d'));
                $sql = 'SELECT COUNT(*) FROM' . prefix('order') . " WHERE member_id={$c->member['id']} AND goods_id={$id} AND is_pay=2 AND created>={$t}";
                $buy_num = p_fetchcolumn($sql) ? : 0;
            }
            if ($buy_num >= $goods['allow_number']) {
                $c->json('每人最多兑换' . $goods['allow_number'] . '件~' , 3);
            }
        }

        if ($goods['exchange_number'] > $c->member['currency']) {
            $c->json('您的数量' . getConfig('currency_name') . '不足~', 3);
        }

        $address = p_get('address', array('member_id' => $c->member['id']));

        $insert = array(
            'goods_id' => $id,
            'member_id' => $c->member['id'],
            'exchange_type' => $goods['exchange_type'],
            'exchange_number' => $goods['exchange_number'],
            'type' => $goods['type'],
            'bag_money' => $goods['bag_money'],
            'money' => $goods['money'],
            'free' => $goods['free'],
            'address' => $address['address'],
            'name' => $address['name'],
            'phone' => $address['phone'],
            'is_pay' => 1,
            'created' => time()
        );

        pdo_begin();
        try{
            $money = 0;
            if ($goods['exchange_type'] == 2 && $goods['money'] > 0) {
                $money = $goods['money'];
            }
            if ($goods['is_free'] == 2 && $goods['free'] > 0) {
                $money += $goods['free'];
            }

            /*$exchange_type = getConfig('exchange_type');
            if ($money <= 0 || $exchange_type == 2) {

                if ($money > 0) {
                    if (!$c->rising->change_money($c->member['id'], $money, 5)) {
                        throw new Exception($c->rising->error);
                    }
                }

                $insert['is_pay'] = 2;
                if (!$c->rising->change_currency($c->member['id'], $goods['exchange_number'], 5)) {
                    throw new Exception($c->rising->error);
                }
                if ($goods['type'] == 2) {
                    if (!$c->rising->change_money($c->member['id'], $goods['bag_money'], 4)) {
                        throw new Exception($c->rising->error);
                    }
                    $insert['status'] = 3;
                    $insert['delivery_time'] = time();
                }
            }*/


            if ($goods['type'] == 3) {

            }


            if (!p_insert('order', $insert)) {
                throw new Exception('兑换失败,请稍后再试');
            }
            $o_id = pdo_insertid();
            if ($money > 0 && $exchange_type != 2) {
                $order_id = $c->rising->unifiedOrder($c->member['id'], $money, $o_id);
                if (!$order_id) {
                    throw new Exception('订单生成失败');
                }


                global $_W;
                $_W['openid'] = $c->member['openid'];
                $_W['member']['uid'] = $c->member['id'];

                if (isQq()) {
                    $notify_url  = $_W['siteroot'] . "app/index.php?i={$_W['uniacid']}&from=wxapp&c=entry&a=wxapp&do=qqCallBack&m=bh_cat";
                    $order  = array(
                        'mch_id'    => getConfig('qq_mch_id'),
                        'nonce_str' => $c->rising->out_trade_no(),
                        'body'      => getConfig('xcx_title').'-' .$goods['goods_name'],
                        'out_trade_no' => $order_id,
                        'fee_type'  => 'CNY',
                        'total_fee' => $money * 100,
                        'spbill_create_ip' => CLIENT_IP,
                        'trade_type' => 'JSAPI',
                        'notify_url' => $notify_url,
                    );
                    $order['sign'] = qqAutograph($order);
                    $s = http_post('https://qpay.qq.com/cgi-bin/pay/qpay_unified_order.cgi', $order);
                    libxml_disable_entity_loader(true);
                    $data = json_decode(json_encode(simplexml_load_string($s, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

                } else {
                    $order = array(
                        'tid' => $order_id, //订单号
                        'fee' => floatval($money), //支付参数
                        'title' => '礼品' . $goods['name'] //标题
                    );
                    $paydata = $this->pay($order);
                    if (is_error($paydata)) {
                        throw new Exception($paydata['message']);
                    }
                    $data = array('paydata' => $paydata);
                }

                pdo_commit();
                $c->json($data, 2);
            }

            pdo_commit();
            $c->json(array('order_id' => $o_id));
        } catch (Exception $e) {
            pdo_rollback();
            $c->json($e->getMessage(), 3);
        }
    }


    /**
     * 兑换
     * @throws Exception
     */
    public function doPageBuy()
    {
        $c = new bhCommon;
        $order_id = intval($c->get('id'));
        $order = p_get('order', array('id' => $order_id, 'member_id' => $c->member['id'], 'status' => 1));
        if (empty($order)) {
            $c->json('订单不存在', 2);
        }
        $goods = p_get('goods', array('id' => $order['goods_id']));

        $all_money = $order['price'] - $order['bargain'];
        $all_money = $all_money > 0 ? $all_money : 0;
        if ($goods['is_free'] == 2 && $goods['free'] > 0) {
            $all_money += $goods['free'];
        }
        if ($order['integral'] > 0 && $c->member['integral'] < $order['integral']) {
            $c->json('兑换所需' . getConfig('integral_name', '积分') . '不足', 2);
        }

        if ($all_money > 0) {
            $order_id = $c->bargain->unifiedOrder($c->member['id'], $all_money, $order_id);
            if (!$order_id) {
                $c->json('订单生成失败', 2);
            }

            p_update('order', array('is_pay' => 2), array('id' => $order_id));

            global $_W;
            $_W['openid'] = $c->member['openid'];
            $_W['member']['uid'] = $c->member['id'];

            $order = array(
                'tid' => $order_id, //订单号
                'fee' => floatval($all_money), //支付参数
                'title' => $goods['name'] //标题
            );
            $paydata = $this->pay($order);
            if (is_error($paydata)) {
                $c->json($paydata['message'], 2);
            }
            $data = array('paydata' => $paydata);

            $c->json($data, 3);

        } else {
            if (!$c->bargain->buy($order_id)) {
                $c->json($c->bargain->error, 2);
            }
            $c->json();
        }

    }



    /**
     *  积分商品生成订单
     */
    public function doPageExchangeGoods()
    {
        $c = new bhCommon;

        $id = $c->get('id');
        if (empty($id)) {
            $c->json('请先选择商品', 3);
        }

        $goods = p_get('integral_goods', array('id' => $id, 'status' => 1, 'is_delete' => 1));

        if (empty($goods)) {
            $c->json('商品不存在或已下架', 3);
        }


        $volume = p_getcolumn('integral_order', array('goods_id' => $id, 'is_pay' => 2), 'COUNT(*)') ? : 0;
        if ($volume >= $goods['inventory']) {
            $c->json('您来晚了,已经被兑换完了~', 3);
        }

        if ($goods['allow_number'] > 0) {
            $buy_num = p_getcolumn('integral_order', array('member_id' => $c->member['id'], 'goods_id' => $id, 'is_pay' => 2), 'COUNT(*)') ? : 0;
            if ($buy_num >= $goods['allow_number']) {
                $c->json('每人最多兑换' . $goods['allow_number'] . '件~' , 3);
            }
        }

        if ($goods['exchange_number'] > $c->member['integral']) {
            $c->json('您的' . getConfig('integral_name') . '不足~', 3);
        }

        $address = p_get('address', array('member_id' => $c->member['id']));

        $insert = array(
            'goods_id' => $id,
            'member_id' => $c->member['id'],
            'exchange_type' => $goods['exchange_type'],
            'exchange_number' => $goods['exchange_number'],
            'type' => $goods['type'],
            'money' => $goods['money'],
            'free' => $goods['free'],
            'address' => $address['address'],
            'name' => $address['name'],
            'phone' => $address['phone'],
            'is_pay' => 1,
            'created' => time()
        );

        pdo_begin();
        try{
            $money = 0;
            if ($goods['exchange_type'] == 2 && $goods['money'] > 0) {
                $money = $goods['money'];
            }
            if ($goods['is_free'] == 2 && $goods['free'] > 0) {
                $money += $goods['free'];
            }

            if ($money <= 0) {
                $insert['is_pay'] = 2;
                if (!$c->bargain->change_integral($c->member['id'], $goods['exchange_number'], 10)) {
                    throw new Exception($c->vote->error);
                }
                if (!p_update('integral_goods', array('exchange_num' => $goods['exchange_num'] + 1), array('id' => $id))) {
                    throw new Exception('兑换失败,请稍后再试');
                }
            }
            if ($goods['type'] == 3) {
                $insert['status'] = 3;
                if (!$c->bargain->change_money($c->member['id'], $goods['red_money'], 5)) {
                    throw new Exception('兑换失败,请稍后再试');
                }
            }

            if (!p_insert('integral_order', $insert)) {
                throw new Exception('兑换失败,请稍后再试');
            }
            $o_id = pdo_insertid();
            if ($money > 0) {
                $order_id = $c->bargain->unifiedOrder($c->member['id'], $money, $o_id, 2);
                if (!$order_id) {
                    throw new Exception('订单生成失败');
                }


                global $_W;
                $_W['openid'] = $c->member['openid'];
                $_W['member']['uid'] = $c->member['id'];

                if (isQq()) {
                    $notify_url  = $_W['siteroot'] . "app/index.php?i={$_W['uniacid']}&from=wxapp&c=entry&a=wxapp&do=qqCallBack&m=bh_vote";
                    $order  = array(
                        'mch_id'    => getConfig('qq_mch_id'),
                        'nonce_str' => $c->bargain->out_trade_no(),
                        'body'      => getConfig('xcx_title').'-' .$goods['goods_name'],
                        'out_trade_no' => $order_id,
                        'fee_type'  => 'CNY',
                        'total_fee' => $money * 100,
                        'spbill_create_ip' => CLIENT_IP,
                        'trade_type' => 'JSAPI',
                        'notify_url' => $notify_url,
                    );
                    $order['sign'] = qqAutograph($order);
                    $s = http_post('https://qpay.qq.com/cgi-bin/pay/qpay_unified_order.cgi', $order);
                    libxml_disable_entity_loader(true);
                    $data = json_decode(json_encode(simplexml_load_string($s, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

                } else {
                    $order = array(
                        'tid' => $order_id, //订单号
                        'fee' => floatval($money), //支付参数
                        'title' => '礼品' . $goods['goods_name'] //标题
                    );
                    $paydata = $this->pay($order);
                    if (is_error($paydata)) {
                        throw new Exception($paydata['message']);
                    }
                    $data = array('paydata' => $paydata);
                }

                pdo_commit();
                $c->json($data, 2);
            }

            pdo_commit();
            $c->json(array('order_id' => $o_id));
        } catch (Exception $e) {
            pdo_rollback();
            $c->json($e->getMessage(), 3);
        }
    }


    /**
     * 充值回调
     */
    public function payResult($data)
    {
        global $_GPC, $_W;
        $orderid = $data['tid'] ? $data['tid'] : $_GPC['orderid'];
        $paylog = pdo_get('core_paylog', array('uniacid' => $_W['uniacid'], 'module' => 'bh_bargain', 'tid' => $orderid));

        $status = intval($paylog['status']) === 1;
        if (!$status) {
            exit;
        }

        $order = pdo_get('bh_bg_pay_order', array('trade_no' => $orderid));

        if (empty($order) || $order['status'] == 2) {
            exit;
        }

        $update = array(
            'transaction_id' => $paylog['encrypt_code'],
            'pay_time' => time(),
            'status' => 2
        );
        pdo_update('bh_bg_pay_order', $update, array('id' => $order['id']));
        //充值后续操作

        $bargain = new bargain();
        if ($order['type'] == 1) {

            $bargain->buy($order['relation_id']);
            /*$o = p_get('order', array('id' => $order['relation_id']));
            $bargain->change_currency($order['member_id'], $o['integral'], 3);

            p_update('order', array('is_pay' => 2, 'status' => 2, 'suc_time' => time()), array('id' => $order['relation_id']));*/
        } else if ($order['type'] == 2) {
            $o = p_get('integral_order', array('id' => $order['relation_id']));
            $bargain->change_currency($order['member_id'], $o['exchange_number'], 10);
            p_update('integral_order', array('is_pay' => 2), array('id' => $order['relation_id']));

            $goods = p_get('integral_goods', array('id' => $o['goods_id']));
            p_update('integral_goods', array('exchange_num' => $goods['exchange_num'] + 1), array('id' => $goods['id']));
        }

        exit('ok');
    }

}